package com.abc.xxx.config.security;

import com.abc.xxx.model.User;
import com.abc.xxx.model.vo.UserInfo;
import com.abc.xxx.service.UserService;
import com.abc.xxx.util.Result;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private JwtService jwtService;
    @Autowired
    private UserService userService;

    @GetMapping("/refresh-token")
    public Result refreshToken(@AuthenticationPrincipal User user, HttpServletResponse res) {
        String oper = "刷新token";
        log.info("==> {}", oper);
        String token = jwtService.createToken(user.getName(), user.getJwtData());
        res.setHeader(AuthHeader.ACCESS_TOKEN, token);
        return Result.success(oper).data("token", token);
    }

    /**
     * 前端存储的vuex store中的用户信息结构
     *   state: {
     *     id: '',
     *     name: '',
     *     nick: '',
     *     root: false,
     *     dept: {
     *       id: null,
     *       name: '',
     *     },
     *     role: {
     *       id: null,
     *       name: '',
     *       dataScope: null,
     *       accessibleViews: []
     *     },
     *   }
     * @param user
     * @return
     */
    @GetMapping("/user-info")
    public Result userInfo(@AuthenticationPrincipal User user) {
        String oper = "获取登录用户信息";
        log.info("==> {}, {}", oper, JSON.toJSONString(user));
        UserInfo userInfo = userService.findUserInfoForLoginedUser(user.getId());
        return Result.success(oper).data("userInfo",userInfo);
    }

}
